﻿using SaaS.Core;
using SaaS.Model.Entity.Sites;
using SaaS.Model.Enums;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using XCore.Dapper;
using XCore.Dependency;
using XCore.Domain.Data;
using XCore.Encryption;
using XCore.Extensions;

namespace Web.System.Services.Sites
{
    /// <summary>
    /// 站点服务
    /// </summary>
    public class SiteAppService : SystemApplicationServiceBase, ISingletonDependency
    {
        /// <summary>
        /// 编辑站点
        /// </summary>
        /// <param name="id"></param>
        /// <param name="name"></param>
        /// <param name="domain"></param>
        /// <param name="connectionString"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public bool Edit(int id, string name, string domain, string connectionString, DatabaseType type)
        {
            if (SDC.Sites.Any(c => c.Id != id && c.Domain == domain)) throw new SystemException($"{domain}：站点前缀已存在", SystemLoggerSource.Site);
            Site site = new Site
            {
                Id = id,
                Name = name,
                Domain = domain,
                ConnectionString = connectionString,
                Type = type
            };
            return Repository.Update(site, c => c.Id == id, c => c.Name, c => c.Domain, c => c.ConnectionString, c => c.Type) && Logger.Log(id, "修改站点资料", site, SystemLoggerSource.Site);
        }

        /// <summary>
        /// 创建站点
        /// </summary>
        /// <param name="name"></param>
        /// <param name="domain"></param>
        /// <returns></returns>
        public bool Create(string name, string domain)
        {
            if (name.IsNullOrWhiteSpace() || name.Length > 32) throw new SystemException("站点名称不能为空，或站点长度不能超过32位字符", SystemLoggerSource.Site);
            if (SDC.Sites.Any(c => c.Domain == domain)) throw new SystemException($"{domain}：站点前缀已存在", SystemLoggerSource.Site);
            using (IDapperDatabase db = CreateDapperDatabase(IsolationLevel.ReadUncommitted))
            {
                string key = MD5Encryption.MD5Salt(32);
                Site site = new Site()
                {
                    Name = name,
                    Domain = domain,
                    SecretKey = key,
                };
                int siteId = db.InsertAndGetId(site);
                if (!this.CreateDefaultAdmin(db, siteId, key))
                {
                    db.RollBack();
                    throw new SystemException("站点管理员添加失败", SystemLoggerSource.Site);
                }
                db.Commit();
                return Logger.Log("添加站点", SystemLoggerSource.Site);
            }
        }
        /// <summary>
        /// 创建默认管理员
        /// </summary>
        /// <param name="db"></param>
        /// <param name="siteId"></param>
        /// <param name="key"></param>
        private bool CreateDefaultAdmin(IDapperDatabase db, int siteId, string key)
        {
            return db.Insert(new SiteAdmin
            {
                SiteId = siteId,
                UserName = CoreSetting.DefaultAdminName,
                Password = PwdEncryption.Encryption(CoreSetting.DefaultPassword, key),
                IsDefault = true,
            });
        }
    }
}
